import requests
import json
import logging
from .config import Config

logger = logging.getLogger(__name__)


class SMSSender:
    def __init__(self):
        self.config = Config()

    def send_sms(self, phone_number, message):
        """发送短信，自动根据配置选择短信提供商。

        选择逻辑：
        1. 如果 SMS_PROVIDER='tencent' 且已配置腾讯云必要项 -> 使用腾讯云SDK
        2. 否则如果配置了阿里云必要项 -> 使用阿里云SDK
        3. 否则回退到 HTTP 示例发送（需用户替换实现）
        """
        try:
            provider = getattr(self.config, 'SMS_PROVIDER', '').lower()

            # 优先按显式指定的 provider
            if provider == 'tencent' and self._has_tencent_config():
                return self._send_tencent_sms(phone_number, message)

            if provider == 'aliyun' and self._has_aliyun_config():
                return self._send_ali_sms(phone_number, message)

            # 否则按可用凭据自动选择
            if self._has_tencent_config():
                return self._send_tencent_sms(phone_number, message)

            if self._has_aliyun_config():
                return self._send_ali_sms(phone_number, message)

            # 最后回退到 HTTP 示例
            return self._send_http_sms(phone_number, message)

        except Exception as e:
            logger.error(f"短信发送失败 {phone_number}: {e}")
            return False

    def _has_tencent_config(self):
        return all([
            getattr(self.config, 'TENCENT_SECRET_ID', ''),
            getattr(self.config, 'TENCENT_SECRET_KEY', ''),
            getattr(self.config, 'TENCENT_SMS_SDK_APPID', ''),
            getattr(self.config, 'TENCENT_TEMPLATE_ID', ''),
        ])

    def _has_aliyun_config(self):
        return all([
            getattr(self.config, 'SMS_ACCESS_KEY', ''),
            getattr(self.config, 'SMS_ACCESS_SECRET', ''),
            getattr(self.config, 'SMS_TEMPLATE_CODE', ''),
        ])

    def _send_tencent_sms(self, phone_number, message):
        """使用腾讯云 SMS SDK 发送短信。

        依赖: pip install tencentcloud-sdk-python
        文档参考: https://cloud.tencent.com/document/product/382/43196
        """
        try:
            # 延迟导入，若未安装则捕获 ImportError 并提示
            from tencentcloud.common import credential
            from tencentcloud.sms.v20210111 import sms_client, models
            from tencentcloud.common.profile.client_profile import ClientProfile
            from tencentcloud.common.profile.http_profile import HttpProfile

            cred = credential.Credential(self.config.TENCENT_SECRET_ID, self.config.TENCENT_SECRET_KEY)

            httpProfile = HttpProfile()
            httpProfile.endpoint = "sms.tencentcloudapi.com"

            clientProfile = ClientProfile(httpProfile=httpProfile)
            client = sms_client.SmsClient(cred, self.config.TENCENT_REGION or 'ap-guangzhou', clientProfile)

            req = models.SendSmsRequest()

            # 规范化手机号为 E.164 格式（示例：+8613711112222）
            if phone_number.startswith('+'):
                phone_e164 = phone_number
            elif phone_number.startswith('86'):
                phone_e164 = f'+{phone_number}'
            else:
                phone_e164 = f'+86{phone_number}'

            params = {
                "PhoneNumberSet": [phone_e164],
                "SmsSdkAppId": self.config.TENCENT_SMS_SDK_APPID,
                "SignName": self.config.SMS_SIGN_NAME,
                "TemplateId": self.config.TENCENT_TEMPLATE_ID,
                # 模板变量列表，若模板需要多个占位请按顺序传入
                "TemplateParamSet": [message]
            }

            req.from_json_string(json.dumps(params))

            resp = client.SendSms(req)

            # resp.SendStatusSet 是列表，每个元素包含 Code 字段，'Ok' 表示成功
            send_status = getattr(resp, 'SendStatusSet', None)
            if send_status and len(send_status) > 0:
                code = getattr(send_status[0], 'Code', '')
                if isinstance(code, str) and code.lower() == 'ok':
                    logger.info(f"腾讯云短信发送成功: {phone_number}")
                    return True
                else:
                    logger.error(f"腾讯云短信发送返回失败: {code} - {getattr(send_status[0], 'Message', '')}")
                    return False

            # 未能获取返回状态，认为失败
            logger.error(f"腾讯云短信发送未知响应: {resp}")
            return False

        except ImportError:
            logger.error("腾讯云 SDK 未安装，请运行: pip install tencentcloud-sdk-python")
            return False
        except Exception as e:
            logger.error(f"腾讯云短信发送异常: {e}")
            return False

    def _send_ali_sms(self, phone_number, message):
        """阿里云短信发送"""
        try:
            # 安装: pip install alibabacloud_dysmsapi20170525
            from alibabacloud_dysmsapi20170525.client import Client
            from alibabacloud_dysmsapi20170525 import models
            from alibabacloud_tea_util.models import RuntimeOptions

            # 配置客户端
            config = alibabacloud_dysmsapi20170525.models.Config(
                access_key_id=self.config.SMS_ACCESS_KEY,
                access_key_secret=self.config.SMS_ACCESS_SECRET,
            )
            config.endpoint = 'dysmsapi.aliyuncs.com'
            client = Client(config)

            # 构建请求
            send_request = models.SendSmsRequest(
                phone_numbers=phone_number,
                sign_name=self.config.SMS_SIGN_NAME,
                template_code=self.config.SMS_TEMPLATE_CODE,
                template_param=json.dumps({'message': message})
            )

            runtime = RuntimeOptions()
            response = client.send_sms_with_options(send_request, runtime)

            if response.body.code == 'OK':
                logger.info(f"短信发送成功: {phone_number}")
                return True
            else:
                logger.error(f"短信发送失败: {response.body.code} - {response.body.message}")
                return False

        except ImportError:
            # 如果未安装阿里云SDK，使用HTTP API
            return self._send_http_sms(phone_number, message)

    def _send_http_sms(self, phone_number, message):
        """HTTP API 方式发送短信（通用）"""
        # 这里使用一个通用的HTTP短信API示例
        # 你需要根据实际使用的短信服务商调整
        payload = {
            'phone': phone_number,
            'message': message,
            'key': self.config.SMS_ACCESS_KEY,
            'secret': self.config.SMS_ACCESS_SECRET
        }

        try:
            response = requests.post(
                'https://your-sms-api.com/send',
                json=payload,
                timeout=10
            )
            response.raise_for_status()
            logger.info(f"HTTP短信发送成功: {phone_number}")
            return True
        except Exception as e:
            logger.error(f"HTTP短信发送失败: {e}")
            return False

    def send_to_family(self, message=None):
        """给所有家人发送短信"""
        if message is None:
            message = self.config.REMINDER_MESSAGE

        results = []
        for phone in self.config.FAMILY_PHONES:
            if phone.strip():
                result = self.send_sms(phone.strip(), message)
                results.append((phone, result))

        logger.info(f"批量发送完成: 共{len(results)}条，成功{sum(1 for _, success in results if success)}条")
        return results